#!/usr/bin/env python
# -*- coding: UTF-8 -*-
"""
@Project ：turbo 
@File    ：handlers.py
@Author  ：赵加响
@Date    ：2023/4/24 13:37 
@Desc    ：
"""
from collections import defaultdict

from apps.rbac.models import RoleMenuOperate, Menu


def init_menu(request):
    """
    初始化前端菜单，以及菜单拥有的操作权限
    """
    current_user = request.user
    roles = current_user.roles.all()

    menu_dict = defaultdict(lambda: {'id': None, 'code': None, 'name': None, 'operate': []})

    for role in roles:
        # 获取该角色下所有绑定的有效菜单操作权限
        red_menus = RoleMenuOperate.objects.filter(role_id=role.id, is_active=True)
        # 不需要设置权限就可以访问的菜单，数据库中Green Light标志为'Y'，例如首页这种任何人都可以看到的菜单
        # Green Light 菜单是不需要和用户进行绑定的
        green_menus = Menu.objects.filter(is_green_light=True, is_active=True)
        for green_menu in green_menus:
            if green_menu.id not in menu_dict:
                menu_dict[green_menu.id] = {'id': green_menu.id, 'code': green_menu.code, 'name': green_menu.name,
                                            'operate': []}

        for red_menu in red_menus:
            menu = red_menu.menu_operate.menu
            menu_id = menu.id
            menu_code = menu.code
            menu_name = menu.name

            menu_dict[menu_id]['id'] = menu_id
            menu_dict[menu_id]['code'] = menu_code
            menu_dict[menu_id]['name'] = menu_name
            menu_dict[menu_id]['operate'].append(red_menu.menu_operate.operate.code)

            get_parent_menus(menu_dict, menu)

    menu_dict = {k: v for k, v in menu_dict.items()}
    return list(menu_dict.values())


def get_parent_menus(menu_dict, menu):
    """
    递归遍历所有的父菜单
    """
    if menu.parent:
        menu = menu.parent
        menu_id = menu.id
        menu_code = menu.code
        menu_name = menu.name

        menu_dict[menu_id]['id'] = menu_id
        menu_dict[menu_id]['code'] = menu_code
        menu_dict[menu_id]['name'] = menu_name
        menu_dict[menu_id]['operate'] = []

        get_parent_menus(menu_dict, menu)
